<?php

class PunchController extends MyClass_Action {
	protected $controller;
	protected $action;
	protected $_user;


	public function init() {

		$this->commonAction();	

	} 
	//查询机构考勤卡情况列表	
	 public function indexAction() {
		try {  	
		     $where='where 1';	
		     $groupid = ( int ) $this->_request->getParam ( 'groups' );
		     $school_id = $this->_request->getParam ( 'school' ); 		
		     $this->view->groups=$groupid; 
		     $this->view->schoolid=$schoolid;  
		  
			 if($school_id){ 
				 $schoolarray=explode('_',$school_id);  
				 $schoolid=$schoolarray['1'];
			 }
			   
			 if($groupid){
				 $where .=' and  a.groupid="'.$groupid.'" ';
				 $this->view->groupid= $groupid; 
			 }
				 
			 if($schoolid){
				 $where .=' and  a.schoolid="'.$schoolid.'" '; 
				 $this->view->schoolid= $school_id; 
			 } 
			 $sql='select  a.schoolid,a.schoolname,b.groupid,b.groupname from school a left join groups b on a.groupid=b.groupid '.$where;	
			 $school=$this->_dbAdapter->fetchAssoc ($sql); 
			 //print_r($school);echo '<br />';
			 $this->view->school= $school;
			 if($schoolid || $groupid){
			 	$where1=' where schoolid in ('.implode(',',array_keys($school)).')';
			 }
			
			$count = 10;
			$curpage = ( int ) $this->_request->getParam ( 'page' );
	     	if (! $curpage)
    				$curpage = 1;
			$this->view->pageNum= $curpage;			
    		$offset = ($curpage - 1) * $count; 

			 $sql="SELECT SQL_CALC_FOUND_ROWS schoolid,count(*) a1,count(case when inuse=1 and isdelete=0 THEN 'use' end) a2,count(case when inuse=0 and isdelete=0 THEN 'nouse' END) a3,count(case when  isdelete=1 THEN 'neveruse' END) a4 from smartcard ".$where1." GROUP BY schoolid limit $offset,$count";
			 $result = $this->_dbAdapter->fetchAssoc ($sql);  
			 //print_r($result);exit;
			 $this->view->result= $result;
    			$param ['file'] = '/' . $this->controller . '/' . $this->action;
    			$param ['totalnum'] = $this->_dbAdapter->fetchOne ( 'SELECT FOUND_ROWS()' ); 
    			$param ['perpagenum'] = $count; // 每页显示的数目
    			$param ['disnum'] = 11; // 取单数显示，当前页停在中间
    			$param ['curpage'] = $curpage; // 当前页码
				$this->view->allnum= $param ['totalnum'];

    			//	require_once 'MyClass/class.page.php';
    			$page = new MyClass_Page ( $param );
    			$page->setvar ( array ('groups' => $groupid,'school'=>$schoolid,'class'=>$classid) );
				$this->view->page= $page->getNumPage ();
		} catch ( Exception $e ) {
			 $this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
	}
	
	
	
	
	//查询已发考勤卡列表	
	 public function detailedAction() {
		try {  	
				  
		     $where='where 1';	
		     $groups = ( int ) $this->_request->getParam ( 'groups' );
		     $school = $this->_request->getParam ( 'school' ); 
		     
		     $schoolid = $this->_request->getParam ( 'sid' ); 
	         $classid  = $this->_request->getParam ( 'class' ); 
		     $cid  = $this->_request->getParam ( 'cid' ); 
			 if($groups)	
		     	$this->view->groups=$groups; 

			 if($schoolid)	
		     	$this->view->school=$groups.'_'.$schoolid;  
			 if($school)
			 	$this->view->school=$school;
		     $this->view->classid=$classid; 
		     $this->view->cid=$cid; 

			   
			 if($school){ 
				 $schoolarray=explode('_',$school);  
				 $schoolid=$schoolarray['1'];
			 }
			   
			 if($groups){
				 $where .=' and  a.groupid="'.$groups.'" ';
				 $this->view->groups= $groups; 
			 }
				 
			 if($schoolid){
				 $where .=' and  a.schoolid="'.$schoolid.'" '; 
				 $this->view->schoolid= $school; 
			 } 
				
			 $sql='select  a.schoolid,a.schoolname,b.groupid,b.groupname from school a left join groups b on a.groupid=b.groupid '.$where;	
			 //echo $sql;echo '<br />';
			 $school=$this->_dbAdapter->fetchAssoc ($sql); 
			 $this->view->school= $school;
			 $where1='';
			 if($schoolid || $groupid){
			 	$where1=' and schoolid in ('.implode(',',array_keys($school)).')';
			 }
			 $where2='';
			 if($classid){
				$where2 .=' and  classid="'.$classid.'" ';
				  $this->view->classid= $classid; 
			 }	
			 $where3='';
			 if($cid){
				$where3.=' and cardid="'.trim($cid).'" ';
				$this->view->cid= $cid; 				 
			 }

			 $sql='select  classid,classname,schoolid from class where isdel=0 '.$where1.$where2;	
			 //echo $sql;echo '<br />';
			 $class=$this->_dbAdapter->fetchAssoc ($sql); 
			 $this->view->class= $class;
			
			$count = 10;
			$curpage = ( int ) $this->_request->getParam ( 'page' );
	     	if (! $curpage)
    				$curpage = 1;
			$this->view->pageNum= $curpage;			
    		$offset = ($curpage - 1) * $count; 

			 $sql="SELECT SQL_CALC_FOUND_ROWS * from smartcard_student_parents where schoolid<>'' and studentid<>'' and isdelete=0  ".$where1.$where3." order by cardid asc  limit $offset,$count";
			 //echo $sql;echo '<br />';exit;
			 $result = $this->_dbAdapter->fetchAssoc ($sql);  
			 
			 $this->view->result= $result;
			 //print_r($result);exit;
    			$param ['file'] = '/' . $this->controller . '/' . $this->action;
    			$param ['totalnum'] = $this->_dbAdapter->fetchOne ( 'SELECT FOUND_ROWS()' ); 
    			$param ['perpagenum'] = $count; // 每页显示的数目
    			$param ['disnum'] = 11; // 取单数显示，当前页停在中间
    			$param ['curpage'] = $curpage; // 当前页码
				$this->view->allnum= $param ['totalnum'];

    			$page = new MyClass_Page ( $param );
    			$page->setvar ( array ('groups' => $groupid,'school'=>$schoolid,'class'=>$classid) );
				$this->view->page= $page->getNumPage ();

			 $sql="SELECT  studentid from smartcard where schoolid<>'' and studentid<>''  ".$where1.$where3." ";
			 $studentid = $this->_dbAdapter->fetchCol ($sql); 
			 if($studentid){ 
				 $sql="select studentid,classid from student_class where inactive=0 and studentid in(".implode(',',$studentid).")";
				 $student_class = $this->_dbAdapter->fetchPairs ($sql); 
				 $this->view->student_class= $student_class;			
			 }
				
		} catch ( Exception $e ) {
			 $this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
	}
	
	
	//注销考勤卡列表	
	 public function deleteAction() {
		try { 
				$cid =   $this->_request->getParam ( 'cid' );  
				
				if(empty($cid)){
				   throw new Exception ( '参数错误！' ); 
				} 
				
			 	$res=$this->_dbAdapter->update ('smartcard',array('isdelete'=>1,'addtime'=>time()),'cardid="'.$cid.'"'); 
			    if($res){
				   $this->feedback ( '已注销', '注意', '/'.$this->controller.'/detailed/cid/'.$cid, 'tip',0); 		 
				}else{
				   $this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
				}  
	 } catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
	 }

	
	 public function sendnewAction() {
		try {  	
				  
		     $where='where 1';	
		     $groupid = ( int ) $this->_request->getParam ( 'groups' );
		     $school_id = $this->_request->getParam ( 'school' ); 		
		     $this->view->groups=$groupid; 
		     $this->view->schoolid=$schoolid;  
		  
			 if($school_id){ 
				 $schoolarray=explode('_',$school_id);  
				 $schoolid=$schoolarray['1'];
			 }
			   
			 if($groupid){
				 $where .=' and  a.groupid="'.$groupid.'" ';
				 $this->view->groupid= $groupid; 
			 }
				 
			 if($schoolid){
				 $where .=' and  a.schoolid="'.$schoolid.'" '; 
				 $this->view->schoolid= $school_id; 
			 } 
			
			$count = 10;
			$curpage = ( int ) $this->_request->getParam ( 'page' );
	     	if (! $curpage)
    				$curpage = 1;
			$this->view->pageNum= $curpage;			
    		$offset = ($curpage - 1) * $count; 

			 $sql="select SQL_CALC_FOUND_ROWS a.schoolid,a.schoolname,b.groupid,b.groupname from school a left join groups b on a.groupid=b.groupid ".$where." limit $offset,$count";	
			 $school=$this->_dbAdapter->fetchAssoc ($sql); 
			 $this->view->school= $school;

    			$param ['file'] = '/' . $this->controller . '/' . $this->action;
    			$param ['totalnum'] = $this->_dbAdapter->fetchOne ( 'SELECT FOUND_ROWS()' ); 
    			$param ['perpagenum'] = $count; // 每页显示的数目
    			$param ['disnum'] = 11; // 取单数显示，当前页停在中间
    			$param ['curpage'] = $curpage; // 当前页码
				$this->view->allnum= $param ['totalnum'];

    			//	require_once 'MyClass/class.page.php';
    			$page = new MyClass_Page ( $param );
    			$page->setvar ( array ('groups' => $groupid,'school'=>$schoolid) );
				$this->view->page= $page->getNumPage ();
		} catch ( Exception $e ) {
			 $this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
	}

	 public function senditAction() {
		try {  	
		     $schoolid = $this->_request->getParam ( 'schoolid' ); 		
			 if(!$schoolid){
				 throw new Exception ( '参数错误！' );
			 } 
			 //$sql='select b.groupname,a.schoolname,a.schoolid,a.groupid from school a left join groups b on a.groupid=b.groupid where a.schoolid='.$schoolid;
			 //$school=$this->_dbAdapter->fetchRow ($sql);
			 $this->view->schoolid= $schoolid;
		} catch ( Exception $e ) {
			 $this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
	}
	
	 public function senditexcleAction() {
		try {  	
		     $schoolid = $this->_request->getParam ( 'schoolid' ); 		
			 if(!$schoolid){
				 throw new Exception ( '参数错误！' );
			 } 
			 $this->view->schoolid= $schoolid;
		} catch ( Exception $e ) {
			 $this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
	}
/****************************/	
	//excel导入数据
	public function senditaddexcelAction(){
		try {
			if (! $this->isPost ()) {
				throw new Exception ( 'parameter_error' );
			}
			$schoolid = $this->_request->getParam ( 'schoolid' );			
			//print_r($schoolid);exit; 
			$succ_result=0;
			$error_result=0;
			$file=$_FILES['filename'];
			//print_r($file);exit;
			$max_size="2000000"; //最大文件限制（单位：byte）
			$fname=$file['name'];
			$ftype=strtolower(substr(strrchr($fname,'.'),1));
			$uploadfile=$file['tmp_name'];
			if(is_uploaded_file($uploadfile)){
	          if($file['size']>$max_size){
		         throw new Exception ( '文件太大只限200兆' );
		      }
			  if($ftype!='xls' && $ftype!='xlsx'){
		         throw new Exception ( 'excel格式错误' );
		      }
			}else{
			     throw new Exception ( '没有上传文件' ); 
			} 
			//$objExcel = new PHPExcel_IOFactory();
			if($ftype=='xls'){
				$objReader = PHPExcel_IOFactory::createReader('Excel5');//use excel2007 for 2007 format 
			}
			else{
				$objReader = PHPExcel_IOFactory::createReader('Excel2007');//use excel2007 for 2007 format 
			}
			$objPHPExcel = $objReader->load($uploadfile); 
			$sheet = $objPHPExcel->getSheet(0); 
			$highestRow = $sheet->getHighestRow(); // 取得总行数 
			$highestColumn = $sheet->getHighestColumn(); // 取得总列数			
			$arr_result=array();
			$strs=array();
			$isnum=0;
			$dutyid=0;
			for($j=2;$j<=$highestRow;$j++)
			 { 
				$stringvalue="";
			    unset($arr_result);
			    unset($strs);
			    //for($k='A';$k<= "E";$k++){
				for($k='A';$k<= $highestColumn;$k++){ 
				     //读取单元格
				 	$stringvalue .= $objPHPExcel->getActiveSheet()->getCell("$k$j")->getValue().',';
				}
				$strs=explode(",",$stringvalue);

			 	if(!trim($strs[1]))
				{
					continue;
				}
				$sql='select cardid from smartcard where schoolid is null and isdelete=0 and cardid ="'.trim($strs[1]).'"';
				
				$have=$this->_dbAdapter->fetchOne ($sql);
				if(empty($have)){
					$str.='卡号：'.trim($strs[1]).'不存在或已占用或已删除<br />';
					continue;	
				}else{					
					$sql='update smartcard set schoolid='.$schoolid.' where cardid ="'.trim($strs[1]).'"';
					$result1=$this->_dbAdapter->query ($sql);
					
				}
				
				//echo "<pre>";var_dump($strs);echo "</pre>";
				if($result1){
					$succ_result+=1;
					$isnum = $isnum+1;
				}else{
					$error_result+=1;
				}
				 
			 }	 
			unlink($uploadfile); 	//删除上传的excel文件
			$this->feedback ("总共".($succ_result+$error_result)."条数据"."<br/>". '导入成功'.$succ_result.'条数据!<br/>插入失败'.$error_result.'条数据!<br/>'.$str.'', 'success', '/'.$this->controller, 'tip', 5 );
		} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
	}
	
	//excel检测
	public function senditdetectexcelAction(){
	try {
			if (! $this->isPost ()) {
				throw new Exception ( 'parameter_error' );
			}
			$schoolid = $this->_request->getParam ( 'schoolid' );			
			$succ_result=0;
			$error_result=0;
			$file=$_FILES['filename'];
			$max_size="2000000"; //最大文件限制（单位：byte）
			$fname=$file['name'];
			$ftype=strtolower(substr(strrchr($fname,'.'),1));
			$uploadfile=$file['tmp_name'];
			if(is_uploaded_file($uploadfile)){
	          if($file['size']>$max_size){
		         throw new Exception ( '文件太大只限200兆' );
		      }
			  if($ftype!='xls' && $ftype!='xlsx'){
		         throw new Exception ( 'excel格式错误' );
		      }
			}else{
			     throw new Exception ( '没有上传文件' ); 
			} 
			//$objExcel = new PHPExcel_IOFactory();
			if($ftype=='xls'){
				$objReader = PHPExcel_IOFactory::createReader('Excel5');//use excel2007 for 2007 format 
			}
			else{
				$objReader = PHPExcel_IOFactory::createReader('Excel2007');//use excel2007 for 2007 format 
			}
			$objPHPExcel = $objReader->load($uploadfile); 
			$sheet = $objPHPExcel->getSheet(0); 
			$highestRow = $sheet->getHighestRow(); // 取得总行数 
			$highestColumn = $sheet->getHighestColumn(); // 取得总列数			
			$arr_result=array();
			$strs=array();
			$isnum=0;
			$dutyid=0;
			$error_string="";
			$error_content="";
			$dutyerror="";
			
			for($j=2;$j<=$highestRow;$j++)
			 { 
			 	
				$stringvalue="";
			    unset($arr_result);
			    unset($strs);
			    for($k='A';$k<= $highestColumn;$k++){//for($k='A';$k<= $highestColumn;$k++){ 
			    	
				     //读取单元格
				 	$stringvalue .= $objPHPExcel->getActiveSheet()->getCell("$k$j")->getValue().',';
				}

				$strs=explode(",",$stringvalue);
				
				if(!trim($strs[1])){
					continue;
				}
				$sql="select cardid from smartcard where schoolid is null and isdelete=0 and cardid ='".trim($strs[1])."'";
				$result = $this->_dbAdapter->fetchAll ($sql);
				if($result)
				{
					$succ_result+=1;
				}else{
					$error_string .="第".$j."行：卡号不存在或已占用或已删除";
					$error_result+=1;
				}
			 	$error_content="错误提示：<br/>".$error_string;
				if($error_result==0){
					$error_content="";
				}
				 
			 }	 
			unlink($uploadfile); 	//删除上传的excel文件
			$this->feedback ("总共".($error_result+$succ_result)."条数据"."<br/>正确<span style='color:#4ab317'>".$succ_result."</span>条。<br/>"."错误<span style='color:red'>".$error_result."</span>条。<br/>".$error_content, 'note', '/'.$this->controller.'/excle', 'tip', 3 );
		} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
	}
	
	 public function storeAction() {
		try {  	
		     $where=' ';	
		     $cid  = $this->_request->getParam ( 'cid' ); 
		     $this->view->cid=$cid; 
				
			 if($cid){
				$where.=' and cardid="'.trim($cid).'" ';
				$this->view->cid= $cid; 				 
			 }
			$count = 10;
			$curpage = ( int ) $this->_request->getParam ( 'page' );
	     	if (! $curpage)
    				$curpage = 1;
			$this->view->pageNum= $curpage;			
    		$offset = ($curpage - 1) * $count; 

			 $sql="SELECT SQL_CALC_FOUND_ROWS * from smartcard where schoolid is NULL ".$where." and isdelete=0  limit $offset,$count";
			 $result = $this->_dbAdapter->fetchAll ($sql);  

			 $this->view->result= $result;
    			$param ['file'] = '/' . $this->controller . '/' . $this->action;
    			$param ['totalnum'] = $this->_dbAdapter->fetchOne ( 'SELECT FOUND_ROWS()' ); 
    			$param ['perpagenum'] = $count; // 每页显示的数目
    			$param ['disnum'] = 11; // 取单数显示，当前页停在中间
    			$param ['curpage'] = $curpage; // 当前页码
				$this->view->allnum= $param ['totalnum'];

    			//	require_once 'MyClass/class.page.php';
    			$page = new MyClass_Page ( $param );
    			//$page->setvar ( array ('groups' => $groupid,'school'=>$schoolid,'class'=>$classid) );
				$this->view->page= $page->getNumPage ();
		} catch ( Exception $e ) {
			 $this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
	}
	
	 public function addstoreAction() {
		try {  	

		} catch ( Exception $e ) {
			 $this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
	}

	 public function excleAction() {
		try {  	

		} catch ( Exception $e ) {
			 $this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
	}
/****************************/	
	//excel导入数据
	public function addexcelAction(){
		try {
			if (! $this->isPost ()) {
				throw new Exception ( 'parameter_error' );
			}
			 
			$succ_result=0;
			$error_result=0;
			$file=$_FILES['filename'];
			$max_size="2000000"; //最大文件限制（单位：byte）
			$fname=$file['name'];
			$ftype=strtolower(substr(strrchr($fname,'.'),1));
			$uploadfile=$file['tmp_name'];
			if(is_uploaded_file($uploadfile)){
	          if($file['size']>$max_size){
		         throw new Exception ( '文件太大只限200兆' );
		      }
			  if($ftype!='xls' && $ftype!='xlsx'){
		         throw new Exception ( 'excel格式错误' );
		      }
			}else{
			     throw new Exception ( '没有上传文件' ); 
			} 
			//$objExcel = new PHPExcel_IOFactory();
			if($ftype=='xls'){
				$objReader = PHPExcel_IOFactory::createReader('Excel5');//use excel2007 for 2007 format 
			}
			else{
				$objReader = PHPExcel_IOFactory::createReader('Excel2007');//use excel2007 for 2007 format 
			}
			$objPHPExcel = $objReader->load($uploadfile); 
			$sheet = $objPHPExcel->getSheet(0); 
			$highestRow = $sheet->getHighestRow(); // 取得总行数 
			$highestColumn = $sheet->getHighestColumn(); // 取得总列数			
			$arr_result=array();
			$strs=array();
			$isnum=0;
			$dutyid=0;
			for($j=2;$j<=$highestRow;$j++)
			 { 
				$stringvalue="";
			    unset($arr_result);
			    unset($strs);
			    //for($k='A';$k<= "E";$k++){
				for($k='A';$k<= $highestColumn;$k++){ 
				     //读取单元格
				 	$stringvalue .= $objPHPExcel->getActiveSheet()->getCell("$k$j")->getValue().',';
				}
				$strs=explode(",",$stringvalue);

			 	if(!trim($strs[1]))
				{
					continue;
				}
				$sql='select cardid from smartcard where cardid ="'.trim($strs[1]).'"';
				
				$have=$this->_dbAdapter->fetchOne ($sql);
				if($have)
					continue;	
				else{					
					$sql='insert into smartcard (cardid,inuse,isdelete) values ("'.trim($strs[1]).'",0,0)';
					$result1=$this->_dbAdapter->query ($sql);
				}
				
				//echo "<pre>";var_dump($strs);echo "</pre>";
				if($result1){
					$succ_result+=1;
					$isnum = $isnum+1;
				}else{
					$error_result+=1;
				}
				 
			 }	 
			unlink($uploadfile); 	//删除上传的excel文件
			$this->feedback ("总共".($succ_result+$error_result)."条数据"."<br/>". '导入成功'.$succ_result.'条数据!<br/>插入失败'.$error_result.'条数据!<br/>', 'success', '/'.$this->controller, 'tip', 5 );
		} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
	}
	
	
	//excel检测
	public function detectexcelAction(){
	try {
			if (! $this->isPost ()) {
				throw new Exception ( 'parameter_error' );
			}
			$succ_result=0;
			$error_result=0;
			$file=$_FILES['filename'];
			$max_size="2000000"; //最大文件限制（单位：byte）
			$fname=$file['name'];
			$ftype=strtolower(substr(strrchr($fname,'.'),1));
			$uploadfile=$file['tmp_name'];
			if(is_uploaded_file($uploadfile)){
	          if($file['size']>$max_size){
		         throw new Exception ( '文件太大只限200兆' );
		      }
			  if($ftype!='xls' && $ftype!='xlsx'){
		         throw new Exception ( 'excel格式错误' );
		      }
			}else{
			     throw new Exception ( '没有上传文件' ); 
			} 
			//$objExcel = new PHPExcel_IOFactory();
			if($ftype=='xls'){
				$objReader = PHPExcel_IOFactory::createReader('Excel5');//use excel2007 for 2007 format 
			}
			else{
				$objReader = PHPExcel_IOFactory::createReader('Excel2007');//use excel2007 for 2007 format 
			}
			$objPHPExcel = $objReader->load($uploadfile); 
			$sheet = $objPHPExcel->getSheet(0); 
			$highestRow = $sheet->getHighestRow(); // 取得总行数 
			$highestColumn = $sheet->getHighestColumn(); // 取得总列数			
			$arr_result=array();
			$strs=array();
			$isnum=0;
			$dutyid=0;
			$error_string="";
			$error_content="";
			$dutyerror="";
			
			for($j=2;$j<=$highestRow;$j++)
			 { 
			 	
				$stringvalue="";
			    unset($arr_result);
			    unset($strs);
			    for($k='A';$k<= $highestColumn;$k++){//for($k='A';$k<= $highestColumn;$k++){ 
			    	
				     //读取单元格
				 	$stringvalue .= $objPHPExcel->getActiveSheet()->getCell("$k$j")->getValue().',';
				}

				$strs=explode(",",$stringvalue);
				
				if(!trim($strs[1])){
					continue;
				}
				$sql="select cardid from smartcard where cardid ='".trim($strs[1])."'";
				$result = $this->_dbAdapter->fetchAll ($sql);
				if($result)
				{
					$error_string .="第".$j."行：卡号已存在";
					$error_result+=1;
				}else{
					$succ_result+=1;
				}
			 	$error_content="错误提示：<br/>".$error_string;
				if($error_result==0){
					$error_content="";
				}
				 
			 }	 
			unlink($uploadfile); 	//删除上传的excel文件
			$this->feedback ("总共".($error_result+$succ_result)."条数据"."<br/>正确<span style='color:#4ab317'>".$succ_result."</span>条。<br/>"."错误<span style='color:red'>".$error_result."</span>条。<br/>".$error_content, 'note', '/'.$this->controller.'/excle', 'tip', 3 );
		} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
	}
	
/***************************/	
	 public function opaddstoreAction() {
		try { 
			if(! $this->isPost ()){
				throw new Exception ( '参数错误！' );
			}
			$p=$this->_request->getPost();
//print_r($p);
			foreach($p as $key=>$value){
				if(!$value){
					throw new Exception ( '参数错误！' );
				}
				//$p[$key]=trim($value);
			}
			$cardid=array();
			for($i=$p['cid'];$i<$p['cid']+$p['num'];$i++){
				$cardid[]=$i;
			}
//print_r($cardid);exit;
			$sql='select cardid from smartcard where cardid in('.implode(',',$cardid).')  ';
			$have=$this->_dbAdapter->fetchAll ($sql);
			if($have)
				throw new Exception ( '卡号已在库存！' );					
			
			$insertData='';
			foreach($cardid as $key=>$value){
				$insertData .='('.$value.',0,0),';			
			}
			$sql='insert into smartcard (cardid,inuse,isdelete) values ' .substr($insertData,0,-1);
			//echo $sql;exit;
			$res=$this->_dbAdapter->query ($sql);
				
			if($res){
			   $this->feedback ( '成功', '注意', '/'.$this->controller.'/store', 'tip',0); 		 
			}else{
			   $this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
			}  
	 } catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
	 }
	
	 public function opsenditAction() {
		try { 
			if(! $this->isPost ()){
				throw new Exception ( '参数错误！' );
			}
			$p=$this->_request->getPost();
			//print_r($p);exit;
			foreach($p as $key=>$value){
				if(!$value){
					throw new Exception ( '参数错误！' );
				}
				$p[$key]=trim($value);
			}
			$card=array();
			for($i=$p['cid'];$i<$p['cid']+$p['num'];$i++){
				$card[]=$i;
			}
			foreach($card as $key=>$value){
				$sql='select cardid from smartcard where cardid="'.$value.'" and schoolid is NULL and isdelete=0 ';
				$one=$this->_dbAdapter->fetchOne ($sql);
				if($one)
					$cardid[]=$one;
				else
					throw new Exception ( '在连续的卡号中有被占用的！' );
			}

			if($cardid){
				$sql='update smartcard set schoolid='.$p['schoolid'].' , addtime="'.time().'" where isdelete=0 and cardid in ('.implode(',',$cardid).') ';
				$res=$this->_dbAdapter->query ($sql);
			}
			    if($res){
				   $this->feedback ( '成功', '注意', '/'.$this->controller.'/sendnew/schoolid/'.$p['schoolid'], 'tip',0); 		 
				}else{
				   $this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
				}  
	 } catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
	 }
	 public function openmoreAction() {
		try {  	
				  
		     $where1='';	
		     $where2='';	
		     $groupid = ( int ) $this->_request->getParam ( 'groups' );
		     $school_id = $this->_request->getParam ( 'school' ); 		
		     $this->view->groups=$groupid; 
		     $this->view->schoolid=$schoolid;  
		  
			 if($school_id){ 
				 $schoolarray=explode('_',$school_id);  
				 $schoolid=$schoolarray['1'];
			 }
			   
			 if($groupid){
				 $where1 .=' and  groupid="'.$groupid.'" ';
				 $this->view->groupid= $groupid; 
			 }
				 
			 if($schoolid){
				 $where2 .=' and  schoolid="'.$schoolid.'" '; 
				 $this->view->schoolid= $school_id; 
			 } 
		if($groupid && $schoolid){
			$sql='select groupid,groupname from groups where 1 '.$where1;
			$group=$this->_dbAdapter->fetchPairs ($sql); 
			$this->view->group= $group;
			//print_r($group);
			$sql='select schoolid,schoolname from school where 1 '.$where2;
			$school=$this->_dbAdapter->fetchPairs ($sql); 
			$this->view->school= $school;
			//print_r($school);
			$count = 10;
			$curpage = ( int ) $this->_request->getParam ( 'page' );
	     	if (! $curpage)
    				$curpage = 1;
			$this->view->pageNum= $curpage;			
    		$offset = ($curpage - 1) * $count; 

			 $sql="select SQL_CALC_FOUND_ROWS classid,classname,groupid,schoolid,count(*) as num from group_student_class_parents_v  where inactive=0  ".$where1.$where2." group by classid limit $offset,$count";	
			 $student=$this->_dbAdapter->fetchAll ($sql); 
			 $this->view->student= $student;
//print_r($student);exit;
    			$param ['file'] = '/' . $this->controller . '/' . $this->action;
    			$param ['totalnum'] = $this->_dbAdapter->fetchOne ( 'SELECT FOUND_ROWS()' ); 
    			$param ['perpagenum'] = $count; // 每页显示的数目
    			$param ['disnum'] = 11; // 取单数显示，当前页停在中间
    			$param ['curpage'] = $curpage; // 当前页码
				$this->view->allnum= $param ['totalnum'];

    			//	require_once 'MyClass/class.page.php';
    			$page = new MyClass_Page ( $param );
    			$page->setvar ( array ('groups' => $groupid,'school'=>$schoolid) );
				$this->view->page= $page->getNumPage ();
		  }
		} catch ( Exception $e ) {
			 $this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
	}
	public function cardlistAction() {
		try {
			if (! $this->isPost ()) {
				throw new Exception ( '参数错误！' );
			}
			$p =$this->_request->getPost ();
			//print_r($p);exit;
			
			if(!$p['htmlid']){
				throw new Exception ( '请选择班级' );
			}
			$result=array(
				'studentnum'=>'',
				'need'=>'',
				'have'=>'',
			);
			foreach($p['htmlid'] as $key=>$value){
				if($p['studentnum'][$value]){
					$result['studentnum']=$result['studentnum']+$p['studentnum'][$value];
				}
			}
			$result['need']=$result['studentnum']*$p['num'];
			
			$sql="select count(*) from smartcard where schoolid=".$p['schoolid']." and studentid is NULL and isdelete=0 ";
			$have = $this->_dbAdapter->fetchOne ($sql); 
			$result['have']=$have;
			//print_r($result);
			
			$sql='select a.schoolname,b.groupname from school a left join groups b on a.groupid=b.groupid where a.schoolid='.$p['schoolid'];
			$school_group = $this->_dbAdapter->fetchRow($sql);
			//print_r($school_group);exit;
			$this->view->school_group= $school_group;			
			$this->view->result= $result;			
			$this->view->num= $p['num'];			
			$this->view->classlist= implode(',',$p['htmlid']);			
			$this->view->schoolid= $p['schoolid'];			

			
			 $sql="select cardid from smartcard where schoolid=".$p['schoolid']." and studentid is NULL and isdelete=0 ";
			 $card = $this->_dbAdapter->fetchCol ($sql);  
			 $this->view->card= $card;
			 //print_r($card);exit;
		} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
	}

	public function opopenmoreAction() {
		try {
			if (! $this->isPost ()) {
				throw new Exception ( '参数错误！' );
			}
			$p =$this->_request->getPost ();
			
			//print_r($p);exit;
			if(!$p['htmlid']){
				throw new Exception ( '请选择卡号' );
			}
			$i=1;
			foreach($p['cardid'] as $key=>$value){
				if($key>$p['htmlid'][0]){
					$i++;
				}
			}
			//print_r($i);exit;
			if($i<$p['need']){
				throw new Exception ( '此卡号往后，数量不足，请重新选择第一张卡' );
			}
			
			$sql='select distinct studentid from group_student_class_parents_v where inactive=0 and classid in ('.$p['classlist'].')';
			$studentid=$this->_dbAdapter->fetchCol ($sql);

			$t=time();
			$start=$p['htmlid'][0];		
			for($i=0;$i<$p['num'];$i++){
				 foreach($studentid as $key=>$value){
					$isok=0;
					$res=$this->_dbAdapter->update ('smartcard',array('studentid'=>$value,'inuse'=>1,'addtime'=>$t),'cardid='.$p['cardid'][$start]);
					if($res){
						$start++;
						$isok=1;
					}
				}
			}
			    if($isok){
				   $this->feedback ( '成功', '注意', '/'.$this->controller.'/seeopenmore/student/'.implode(',',$studentid).'/time/'.$t, 'tip',0); 
				}else{
				   $this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
				}  
		} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
	}

	public function seeopenmoreAction() {
		try {
			$students = $this->_request->getParam ( 'student' );
			$time = $this->_request->getParam ( 'time' );
			$this->view->students= $students;
			$this->view->time= $time;
			if(!$students ||!$time){
				throw new Exception ( '参数错误' );
			}
			$stuone=explode(',',$students);
			$sql='select a.groupname,b.schoolname from groups a left join school b on a.groupid=b.groupid left join student c on c.schoolid=b.schoolid where c.studentid='.$stuone[0];
			$stuone=$this->_dbAdapter->fetchRow ( $sql );
			//print_r($stuone);
			
			$sql="select studentid,classname,cnname,mobile from student_class_v where inactive=0 and studentid in (".$students.")";
			$student=$this->_dbAdapter->fetchAssoc ( $sql );
			//print_r($student);
			
			$sql='select cardid,schoolid,studentid,inuse,isdelete,from_unixtime(addtime,"%Y-%m-%d") as addtime from `smartcard` where inuse=1 and isdelete=0 and studentid in ('.$students.')';
			$smartcard=$this->_dbAdapter->fetchAll ( $sql );
			$this->view->student= $student;
			$this->view->smartcard= $smartcard;
			$this->view->stuone= $stuone;
			//print_r($smartcard);exit;
		} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
	}


   public function groupsAction() {
		try { 
		 $p =$this->_request->getPost ();
         $sql="select * from  groups ";
	     $result = $this->_dbAdapter->fetchAll ($sql);
		 
		 $str.='<option value="0" >==请选择机构==</option>';
		 for($i = 0; $i<count($result); $i++)
		{
			$str .= "<option";
			if($p['jigouid']==$result[$i]['groupid']){
				$str .=" selected=selected ";
			}
	      $str .= " value='".$result[$i]['groupid']."'>".$result[$i]['groupname']."</option>";
		}
		  
	    echo $str;  exit;
	} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
	}
	
	//获取所有的校园列表
	  public function schoollistAction() {
		try { 
           if (! $this->isPost ()) {
					throw new Exception ( '参数错误！' );
			}			
		  $p =$this->_request->getPost (); 
		   
		  $array=explode('_',$p['sid']);
		  
		  $sql="SELECT * FROM `groups` where groupid='".$p['id']."' ";
		  $result = $this->_dbAdapter->fetchRow ($sql);
		    $sql="select * from  school where groupid='".$p['id']."' ";   
			$schoollist=$this->_dbAdapter->fetchAll ($sql);
	                 
            $str.='<option value="0" >==请选择学校==</option>';
			// echo $p['id'];   exit;
		 for($i = 0; $i<count($schoollist); $i++)
		{
		  $str .= "<option ";
		  
		  if ($array['1']==$schoollist[$i]['schoolid']){
		      $str .=" selected=selected";
		  }
		   $str .= " value='".$p['id'].'_'.$schoollist[$i]['schoolid']."'>";
		   $str .= $schoollist[$i]['schoolname']."</option>";
		   
		}
		   
	      echo $str;  exit;
	} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
	}
	
	
	
	//获取所有的班级信息
	  public function classlistAction() {
		try { 
           if (! $this->isPost ()) {
					throw new Exception ( '参数错误！' );
			}			
		    $p =$this->_request->getPost ();  
		    $array=explode('_',$p['id']); 
			 
		    $sql="SELECT * FROM `groups` where groupid='".$array['0']."' ";
		    $result = $this->_dbAdapter->fetchRow ($sql);
	      
		  $sql="select * from  class  where isdel=0 and schoolid='".$array[1]."' ";   
		  $classlist= $this->_dbAdapter->fetchAll ($sql);
	      $str.='<option value="0" >==请选择班级==</option>';
		  	 
		 for($i = 0; $i<count($classlist); $i++)
		{
		  $str .= "<option ";
		  if($p['cid']==$classlist[$i]['classid']){
		     $str .=" selected=selected";
		  } 
		  $str .= "  value='".$classlist[$i]['classid']."'>".$classlist[$i]['classname']."</option>";
		    
		} 
		   
	      echo $str;  exit;
	} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
	}
	
//index导出	
	public function indexlistAction() {
		try {  
			    $PHPWord = new PHPWord(); 
				$section = $PHPWord->createSection();
			  
			$students = $this->_request->getParam ( 'students' );
			$time = $this->_request->getParam ( 'time' );
			if(!$students ||!$time){
				throw new Exception ( '参数错误' );
			}
			$stuone=explode(',',$students);
			$sql='select a.groupname,b.schoolname from groups a left join school b on a.groupid=b.groupid left join student c on c.schoolid=b.schoolid where c.studentid='.$stuone[0];
			$stuone=$this->_dbAdapter->fetchRow ( $sql );
			//print_r($stuone);
			
			$sql="select studentid,classname,cnname,mobile from student_class_v where inactive=0 and studentid in (".$students.")";
			$student=$this->_dbAdapter->fetchAssoc ( $sql );
			//print_r($student);
			
			$sql='select cardid,schoolid,studentid,inuse,isdelete,from_unixtime(addtime,"%Y-%m-%d") as addtime from `smartcard` where inuse=1 and isdelete=0 and studentid in ('.$students.') and addtime="'.$time.'"';
			$smartcard=$this->_dbAdapter->fetchAll ( $sql );
			
			foreach($smartcard as $key=>$value){
				$smartcard[$key]['classname']=$student[$value['studentid']]['classname'];
				$smartcard[$key]['cnname']=$student[$value['studentid']]['cnname'];
				$smartcard[$key]['mobile']=$student[$value['studentid']]['mobile'];
			}

				
				$section->addText($stuone['groupname'].'--'.$stuone['schoolname'], array('name'=>'黑体', 'size'=>14, 'bold'=>true,'align'=>'center', 'spaceAfter'=>500));
				
				$section->addTextBreak(1); 
				$PHPWord->addParagraphStyle('pStyle', array('align'=>'center', 'spaceAfter'=>100));
				$table = $section->addTable();
				$table->addRow(500); 
				$section->addTextBreak(1); 
				$table->addCell(1000)->addText("序号", array('name'=>'黑体', 'size'=>14, 'bold'=>true),'pStyle');
				$table->addCell(1500)->addText("班级", array('name'=>'黑体', 'size'=>14, 'bold'=>true),'pStyle');
				$table->addCell(1200)->addText("学生", array('name'=>'黑体', 'size'=>14, 'bold'=>true),'pStyle');
				$table->addCell(2000)->addText("家长手机", array('name'=>'黑体', 'size'=>14, 'bold'=>true),'pStyle');
				$table->addCell(1500)->addText("卡号", array('name'=>'黑体', 'size'=>14, 'bold'=>true),'pStyle');
				$table->addCell(2000)->addText("开卡时间", array('name'=>'黑体', 'size'=>14, 'bold'=>true),'pStyle');
			 	for($r = 0; $r < count($smartcard); $r++) { // Loop through rows
					// Add row
				  $table->addRow(500);
				 
				  $table->addCell(1000)->addText($r+1, array('name'=>'黑体', 'size'=>14, 'bold'=>false),'pStyle');
				  $table->addCell(1500)->addText($smartcard[$r]['classname'], array('name'=>'黑体', 'size'=>14, 'bold'=>false),'pStyle');
				  $table->addCell(1200)->addText($smartcard[$r]['cnname'], array('name'=>'黑体', 'size'=>14, 'bold'=>false),'pStyle');
				  $table->addCell(2000)->addText($smartcard[$r]['mobile'], array('name'=>'黑体', 'size'=>14, 'bold'=>false),'pStyle');
				  $table->addCell(1500)->addText($smartcard[$r]['cardid'], array('name'=>'黑体', 'size'=>14, 'bold'=>false),'pStyle');
				  $table->addCell(2000)->addText($smartcard[$r]['addtime'], array('name'=>'黑体', 'size'=>14, 'bold'=>false),'pStyle');
				}

				$fileName = $stuone['groupname'].'--'.$stuone['schoolname'];
				header("Content-type: application/vnd.ms-word");
				header("Content-Disposition:attachment;filename=".$fileName.".docx"); 
				header('Cache-Control: max-age=0');
				
				$objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007'); 
				$objWriter->save('php://output');					 
				  
				exit; 
	} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning',3 );
		}
	}
	  
  /*
  操作处理end
  */	
	public function log($message){        
		$log=Zend_Registry::get("logger");
		$log->setEventItem('modules', $this->_request->getModuleName() );
		$log->setEventItem('controller', $this->_request->getControllerName() );
		$log->setEventItem('action', $this->_request->getActionName() );
		$log->log($message,8);
		//使用方法	$this->log(var_export($course, true));
	}
	 //以下内容保持不变
	public function noRouteAction() {
		$this->_redirect ( '/' );
	}
	
	public function __call($method, $args) {
		if ('Action' == substr ( $method, - 6 )) {
			$url = '/' . $this->controller . '/index';
			return $this->_redirect ( $url );
		}
		throw new Exception ( 'Invalid method' );
	}}

